package com.etrans.web.gps.business.report.controller;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.etrans.web.gps.base.controller.BaseController;
import com.etrans.web.gps.business.report.domain.LngLat;
import com.etrans.web.gps.business.report.domain.TourismViolationVO;
import com.etrans.web.gps.business.report.service.TourismViolationService;
import com.etrans.web.gps.business.system.service.CommonService;
import com.etrans.web.gps.common.page.PageVo;
import com.etrans.web.gps.util.Config;
import com.etrans.web.gps.util.grid.FlexiGridUtil;

/**
 * @Description:
 * 旅游违规运营分析（旅游无包车牌异常）Controller
 * @author zhangw
 * 
 */
@Controller
@RequestMapping("/report/tourismViolation/")
public class TourismViolationController extends BaseController{
	
	private final static Logger logger = LoggerFactory.getLogger(TourismViolationController.class);

	@Autowired
	private TourismViolationService tourism;
	
	@Autowired
	private Config config; //引用统一的参数配置类 
	
	@Autowired
	private CommonService commonService;
	
	/**
	 * 页面跳转
	 * @return view页面
	 */
	@RequestMapping("getTourismViolation.html")
	public String getTourismViolation(){
		return "views/business/report/tourismViolation";
	}
	
	/**
	 * 查询登录用户权限下的全部的旅游车辆
	 * @param area_id 区域编号   
	 * @return  车辆所有信息
	 */
	@ResponseBody
	@RequestMapping("getVesByRoleAndKind.html")
	public  List<HashMap<String,Object>> queryVesByRoleAndKind(){
		int area_id= this.getSysUser().getArea_id();
		String vehicle_no = request.getParameter("name");
		return tourism.queryVeListByRoleAndKind(area_id,vehicle_no);
	}
	
	/**
	 * 查询登录用户权限下的业户
	 * @return  业户信息列表
	 */
	@ResponseBody
	@RequestMapping("getEnterpirseList.html")
	public  List<HashMap<String,Object>> getEnterpirseList(HttpServletRequest request){
		String name = request.getParameter("name");
		int area_id= this.getSysUser().getArea_id();
		return tourism.queryEnterAndPlatByRole(area_id,name);
	}
	
	/**
	 * 根据查询条件查询
	 * @return 获取柱状图查询数据
	 */
	@ResponseBody
	@RequestMapping("getBarChartData.html")
	public Map<String,Object> getBarChartData(){
		Map<String,Object> map =new HashMap<String, Object>();
		try {
			//权限限制
			int areaId= this.getSysUser().getArea_id();
			Map<String,Object> params = getReqParameters();
			String startTime = params.get("startTime") == null? "" : String.valueOf(params.get("startTime"));
			String endTime = params.get("endTime") == null? "" : String.valueOf(params.get("endTime"));
			String queryType = params.get("queryType") == null? "" : String.valueOf(params.get("queryType"));
			String queryContent = params.get("queryContent") == null? "" : String.valueOf(params.get("queryContent"));
			map = tourism.queryBarChartData(areaId, startTime, endTime, queryType, queryContent);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	/**
	 * 根据业户id和查询时间
	 * @return 单个业户一天24小时的异动车辆数量
	 */
	@ResponseBody
	@RequestMapping("loadDetailLineChartData.html")
	public Map<String,Object> loadDetailLineChartData(){
		Map<String,Object> map =new HashMap<String, Object>();
		try {
			Map<String,Object> params = getReqParameters();
			String startTime = params.get("startTime") == null? "" : String.valueOf(params.get("startTime"));
			String endTime = params.get("endTime") == null? "" : String.valueOf(params.get("endTime"));
			String enterprise = params.get("enterprise") == null? "" : String.valueOf(params.get("enterprise"));
			map = tourism.queryLineChartData(startTime, endTime, enterprise);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
		return map;
	}
	
	/**
	 * 根据业户名和查询时间查询
	 * @return  登录用户权限下的全部业户的旅游异动车辆
	 */
	@ResponseBody
	@RequestMapping(value = "getResultTableByEnt.html")
	public PageVo getResultTableByEnt(){
		PageVo pageVo = new PageVo();
		try {
			//权限
			int areaId= this.getSysUser().getArea_id();
			//获取查询条件
			Map<String,Object> paramMaps = getReqParameters();
			String paramsGrid = String.valueOf(paramMaps.get("paramsGrid"));
			Map<String, Object> params = FlexiGridUtil.parseJSONParam(paramsGrid).getWhereParam();
			Integer size = Integer.parseInt(String.valueOf(params.get("pageSize")));
			Integer page = Integer.parseInt(String.valueOf(params.get("page")));
			String startTime = params.get("startTime") == null? "" : String.valueOf(params.get("startTime"));
			String endTime = params.get("endTime") == null? "" : String.valueOf(params.get("endTime"));
			String queryType = params.get("queryType") == null? "" : String.valueOf(params.get("queryType"));
			String queryContent = params.get("queryContent") == null? "" : String.valueOf(params.get("queryContent"));
			Integer total = tourism.queryTourismTableCount(areaId, startTime, endTime, queryType, queryContent);
			List<TourismViolationVO> tourismVeList = 
				tourism.queryTourismTable(areaId, startTime, endTime, queryType, queryContent, (page-1)*size, size);
			//获取车辆颜色Map
			Map<String,Object> colorMap = new HashMap<String,Object>();
			List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
			for (HashMap<String, Object> hashMap : colorList) {
				colorMap.put(String.valueOf(hashMap.get("id")), hashMap.get("name"));
			}
			//遍历取值
			Integer index = (page-1)*size+1;
			for (TourismViolationVO tourismVe : tourismVeList) {
				tourismVe.setIndex(index++);
				String colorName = String.valueOf(colorMap.get(String.valueOf(tourismVe.getVehicle_color())));
				tourismVe.setVehicle_color_name(colorName);
				double[] Coordinates = tourismVe.getCoordinates().getCoordinates();
				if (Coordinates.length > 1) {
					tourismVe.setLongitude(Coordinates[0]);
					tourismVe.setLatitude(Coordinates[1]);
				}
			}
			pageVo.setTotal(total);
			pageVo.setRows(tourismVeList);
			pageVo.setPage(page);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
        return pageVo;
	}
	

	/**
	 * 导出报表
	 * @param response
	 * @param request
	 * @param paramsGrid 前端json格式的参数
	 * @param colModel 表头
	 * @param title 标题
	 * @param imgsrc 图片url,如果为null则不加载图片页
	 */
	@SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="exportResultTable.html")
	@ResponseBody
	public void exportDriver(HttpServletResponse response,HttpServletRequest request, String startTime, String endTime,
			String queryType, String queryContent, String StartSize,String pageSize,
			String colModel, String title, String imgsrc){
		try {
			//权限
			int areaId= this.getSysUser().getArea_id();
			//获取查询条件
			Integer from = Integer.parseInt(StartSize);
			Integer size = Integer.parseInt(pageSize);
			List<TourismViolationVO> tourismVeList = 
				tourism.queryTourismTable(areaId, startTime, endTime, queryType, queryContent, from, size);
			//获取车辆颜色Map
			Map<String,Object> colorMap = new HashMap<String,Object>();
			List<HashMap<String, Object>> colorList = commonService.queryVehicleColorList(null);
			for (HashMap<String, Object> hashMap : colorList) {
				colorMap.put(String.valueOf(hashMap.get("id")), hashMap.get("name"));
			}
			//遍历取值
			Integer index = from + 1;
			for (TourismViolationVO tourismVe : tourismVeList) {
				tourismVe.setIndex(index++);
				String colorName = String.valueOf(colorMap.get(String.valueOf(tourismVe.getVehicle_color())));
				tourismVe.setVehicle_color_name(colorName);
				double[] Coordinates = tourismVe.getCoordinates().getCoordinates();
				if (Coordinates.length > 1) {
					tourismVe.setLongitude(Coordinates[0]);
					tourismVe.setLatitude(Coordinates[1]);
				}
			}
			List<String> colModelList = JSON.parseObject(colModel, List.class);	
			List<String> imgsrcList   = JSON.parseObject(imgsrc, List.class);
			List<HashMap<String, Object>> rows = new ArrayList<HashMap<String, Object>>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");
			for(int i=0;i<tourismVeList.size();i++){
				HashMap<String, Object> map = new HashMap<String, Object>();
				TourismViolationVO  tourismVe=(TourismViolationVO)tourismVeList.get(i);
				map.put("index",tourismVe.getIndex() == null ? "" : tourismVe.getIndex());
				map.put("vehicle_no",tourismVe.getVehicle_no()== null ? "" : tourismVe.getVehicle_no());
				map.put("vehicle_color_name",tourismVe.getVehicle_color_name() == null ? "" : tourismVe.getVehicle_color_name());
				map.put("enterprise_name",tourismVe.getEnterprise_name() == null ? "" : tourismVe.getEnterprise_name());
				map.put("gps_time",tourismVe.getGps_time() == null ? "" : sdf.format(tourismVe.getGps_time()));
				map.put("coordinates",tourismVe.getCoordinates() == null ? "" : getLocation(tourismVe.getCoordinates()));
				rows.add(map);
			}	
			List rowsList = new ArrayList<>();
			rowsList.add(rows);
			exportExl(request, response,title, removeHeadName(colModelList,-1,-1),rowsList,imgsrcList);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e.getMessage());
		}
	}
	
	/**
	 * 根据经纬度获取地理位置
	 * @param jsonObject 经纬度
	 * @return           地理位置
	 */
	public  String getLocation(LngLat coordinates){
		StringBuffer buff = new StringBuffer();
		String URL =config.addressPath+"?location="+coordinates.getCoordinates()[0]+","+coordinates.getCoordinates()[1];
		HttpPost httpPost = new HttpPost(URL);
		CloseableHttpClient client = HttpClientBuilder.create().build();
		String str =null;
		try {
			HttpResponse response = client.execute(httpPost);
			InputStream in = response.getEntity().getContent();
			InputStreamReader isr = new InputStreamReader(in);
			BufferedReader bfr =new  BufferedReader(isr);
			while((str=bfr.readLine())!=null){
				buff.append(str);
			}
			bfr.close();
			JSONObject json = JSONObject.parseObject(buff.toString());
			str = json.get("regeocodes").toString();
			str = str.substring(1,str.length()-1);
			json = JSONObject.parseObject(str);
			str = json.get("formatted_address").toString();
		} catch (Exception e) {
			e.printStackTrace();
			logger.error("导出位置获取失败");
		}
		return str;
	}
}